{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch:1000 loss:0.650059\n",
      "epoch:2000 loss:0.008774\n",
      "epoch:3000 loss:0.086917\n",
      "epoch:4000 loss:0.983347\n",
      "epoch:5000 loss:0.093300\n",
      "dog\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sentences = [\"i like dog\", \"i love coffee\", \"i hate milk\"]\n",
    "\n",
    "n_hidden = 5\n",
    "n_step = 2\n",
    "\n",
    "word_dict = ' '.join(sentences).split()\n",
    "word_dict = list(set(word_dict))\n",
    "word_num = {w:i for i,w in enumerate(word_dict)}\n",
    "num_word = {i:w for i,w in enumerate(word_dict)}\n",
    "n_class = len(word_num)\n",
    "\n",
    "def get_batch(sentences):\n",
    "    input_batch = []\n",
    "    target_batch = []\n",
    "  \n",
    "    for sen in sentences:\n",
    "        word = sen.split()\n",
    "        input_temp = [word_num[w] for w in word[:-1]]\n",
    "        target_temp = word_num[word[-1]]\n",
    "        \n",
    "        input_batch.append(np.eye(n_class)[input_temp])\n",
    "        target_batch.append(np.eye(n_class)[target_temp])\n",
    "        \n",
    "    return input_batch,target_batch\n",
    "\n",
    "X = tf.placeholder(tf.float32,[None,n_step,n_class])\n",
    "Y = tf.placeholder(tf.float32,[None,n_class])\n",
    "\n",
    "W = tf.Variable(tf.random_normal([n_hidden,n_class]))\n",
    "b = tf.random_normal([n_class])\n",
    "\n",
    "#model\n",
    "cell = tf.contrib.rnn.BasicRNNCell(n_hidden)\n",
    "cell = tf.contrib.rnn.DropoutWrapper(cell,output_keep_prob=0.5)\n",
    "hidden_outputs,last_outputs = tf.nn.dynamic_rnn(cell,X,dtype=tf.float32)# [n_step, batch_size, n_hidden]\n",
    "hidden_outputs = tf.transpose(hidden_outputs,[1,0,2]) #[n_step, batch_size, n_hidden]\n",
    "outputs = hidden_outputs[-1]#[batch_size, n_hidden]\n",
    "\n",
    "out = tf.matmul(outputs,W) + b #[batch_size,n_class]\n",
    "\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y,logits=out))\n",
    "optimizer = tf.train.AdamOptimizer(0.001).minimize(cost)\n",
    "\n",
    "predict = tf.cast(tf.argmax(out,1),tf.int32)\n",
    "\n",
    "input_batch,target_batch = get_batch(sentences)\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    for i in range(5000):\n",
    "        _,loss = sess.run([optimizer,cost],feed_dict={X:input_batch,Y:target_batch})\n",
    "        \n",
    "        if (i+1)%1000 == 0:\n",
    "            print('epoch:%d loss:%.6f' % ((i+1),loss))\n",
    "        \n",
    "    test = [\"i like dog\"]\n",
    "    test_x,_ = get_batch(test)\n",
    "    pre = sess.run(predict,feed_dict={X:test_x})\n",
    "    print(num_word[pre[0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
